<template>
  <div>
    <a-card style="margin-top: 12px;">
      <div>
        <a-form-model layout="horizontal" :model="form" ref="queryForm" :labelCol="{span: 7}" :wrapperCol="{span: 17, offset: 0}">
          <div class="fold">
            <a-row>
              <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <a-form-model-item
                  label="机构名称"
                  prop="name"
                >
                  <a-input v-model="form.name" />
                </a-form-model-item>
              </a-col>
              <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <a-form-model-item
                  label="负责人"
                  prop="leader"
                >
                  <a-input v-model="form.leader" />
                </a-form-model-item>
              </a-col>
              <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <a-form-model-item
                  label="类型"
                  prop="type"
                >
                  <a-select allowClear v-model="form.type" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
                    <a-select-option v-for="item in dict.type" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :xxl="6" :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                <a-form-model-item
                  label="状态"
                  prop="status"
                >
                  <a-select allowClear v-model="form.status" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}">
                    <a-select-option v-for="item in dict.status" :key="item.key" :value="item.value">{{item.title}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row type="flex" justify="end">
              <a-button @click="submitForm" type="primary">查询</a-button>
              <a-button @click="resetForm" style="margin-left: 8px">重置</a-button>
            </a-row>
          </div>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 12px;">
      <div>
        <div>
          <a-button class="space-vertical" @click="showAddModal" type="primary" v-auth="`config:organization:add`">新增</a-button>
        </div>
        <div class="alert">
          <a-alert type="info" :show-icon="true">
            <div class="message" slot="message">
              共 <a>{{total}}</a> 条记录
            </div>
          </a-alert>
        </div>
        <standard-table
          ref="table"
          :size="`middle`"
          :bordered="false"
          :striped="false"
          :isPagination="false"
          :loading="loading"
          :columns="columns"
          :dataSource="dataSource"
          :expandedRowKeys="expandedRowKeys"
          :onExpand="onExpand"
        >
          <div slot="action" slot-scope="{text, record}">
            <a @click="showQueryModal(record.id)" v-auth="`config:organization:query`">
              查看
            </a>
            <a-divider v-if="record.type != 2" class="row-btn-divider" type="vertical" v-auth="`config:organization:add`"/>
            <a v-if="record.type != 2" @click="showAddHasParentModal(record.id, record.type)" v-auth="`config:organization:add`">
              新增
            </a>
            <a-divider class="row-btn-divider" type="vertical" v-auth="`config:organization:edit`"/>
            <a @click="showEditModal(record.id)" v-auth="`config:organization:edit`">
              编辑
            </a>
            <a-divider v-if="record.type != 0" class="row-btn-divider" type="vertical" v-auth="`config:organization:delete`"/>
            <a v-if="record.type != 0" @click="showDeleteModal(record.id)" v-auth="`config:organization:delete`">
              删除
            </a>
          </div>
          <div slot="code" slot-scope="{text}">
            <a-tag color="blue" v-if="text">{{text}}</a-tag>
            <span v-else>{{text}}</span>
          </div>
          <div slot="status" slot-scope="{text}">
            <a-badge :status="text == 1 ? 'success' : 'error'" :text="text | dictFilter(dict.status)"/>
          </div>
          <div slot="type" slot-scope="{text}">
           {{text | dictFilter(dict.type)}}
          </div>
        </standard-table>
      </div>
      <add-modal
        ref="addModal"
        :visible="visibleAddModal"
        @cancel="hideAddModal"
        @ok="addSuccess"
      />
     <edit-modal
        ref="editModal"
        :visible="visibleEditModal"
        @cancel="hideEditModal"
        @ok="editSuccess"
      />
      <query-modal
        ref="queryModal"
        :visible="visibleQueryModal"
        @cancel="hideQueryModal"
      />
    </a-card>
  </div>
</template>

<script>
import StandardTable from '@/components/table/standard-table'
import AddModal from './add-modal'
import EditModal from './edit-modal'
import QueryModal from './query-modal'
import {organizationService} from '@/services'

const columns = [
  {
    title: '机构名称',
    dataIndex: 'name',
    width: 240
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 120,
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '负责人',
    dataIndex: 'leader',
    width: 180
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    width: 180
  },
  {
    title: '排序',
    dataIndex: 'sort',
    width: 100
  },
  // {
  //   title: '创建时间',
  //   dataIndex: 'createTime',
  //   width: 160
  // },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 160
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120,
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    width: 220,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'Organization',
  components: { StandardTable, AddModal, EditModal, QueryModal },
  data () {
    return {
      loading: false,
      confirmLoading: false,
      advanced: false,
      columns: columns,
      dataSource: [],
      expandedRowKeys: [],
      total: 0,
      form: {
        type: undefined,
        name: undefined,
        leader: undefined,
        status: undefined
      },
      dict: {
        status: [],
        type: []
      },
      visibleAddModal: false,
      visibleEditModal: false,
      visibleQueryModal: false
    }
  },
  filters: {
    dictFilter: (val, dictList) => {
      const dict = dictList.find(item => item.value == val)
      return dict ? dict.title : '未知'
    }
  },
  authorize: {
    showQueryModal: 'config:organization:query',
    showAddModal: 'config:organization:add',
    showAddHasParentModal: 'config:organization:add',
    showEditModal: 'config:organization:edit',
    showDeleteModal: 'config:organization:delete'
  },
  methods: {
    onExpand(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id);
      }
      else {
        this.expandedRowKeys = this.expandedRowKeys.filter(key => key != record.id)
      }
    },
    reloadTable() {
      this.queryListAction()
    },
    resetForm() {
      this.$refs.queryForm.resetFields()
      this.reloadTable()
    },
    submitForm() {
      this.reloadTable()
    },
    showAddModal() {
      this.visibleAddModal = true
    },
    showAddHasParentModal(key, type) {
      this.visibleAddModal = true
      this.$refs.addModal.form.type = (parseInt(type) + 1).toString()
      this.$refs.addModal.queryParentTreeAction(key)
    },
    showEditModal(key) {
      this.visibleEditModal = true
      this.$refs.editModal.queryParentTreeAction()
      this.$refs.editModal.queryAction(key)
    },
    showQueryModal(key) {
      this.visibleQueryModal = true
      this.$refs.queryModal.queryParentTreeAction()
      this.$refs.queryModal.queryAction(key)
    },
    hideAddModal() {
      this.visibleAddModal = false
      this.$refs.addModal.$refs.form.resetFields()
    },
    hideEditModal() {
      this.visibleEditModal = false
      this.$refs.editModal.$refs.form.resetFields()
    },
    hideQueryModal() {
      this.visibleQueryModal = false
      this.$refs.queryModal.$refs.form.resetFields()
    },
    addSuccess() {
      this.hideAddModal()
      this.reloadTable()
    },
    editSuccess() {
      this.hideEditModal()
      this.reloadTable()
    },
    deleteAction(keys) {
      this.confirmLoading = true
      const params = {
        ids: keys
      }
      return organizationService.del(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.$message.success(result.msg)
          this.selectedRows = []
          this.reloadTable()
        }
      }).finally(this.confirmLoading = false)
    },
    showDeleteModal (key) {
      this.$confirm({
        confirmLoading: this.confirmLoading,
        icon: 'info-circle',
        title: '警告',
        content: '你确定要删除此项吗？',
        okType: 'danger',
        onOk:() => {
          this.deleteAction([key])
        },
        onCancel() {},
      })
    },
    queryListAction() {
      this.loading = true
      const params = this.form
      organizationService.queryList(JSON.stringify(params)).then(res => {
        const result = res.data
        if (result.code === 200) {
          this.dataSource = []
          this.expandedRowKeys = []
          this.total = result.data.totalCount
          this.dataSource = result.data.records
          this.expandAllTreeNode(this.dataSource, this.expandedRowKeys)
        }
      }).finally(this.loading = false)
    },
    expandAllTreeNode(originData, targetData) {
      originData.forEach(item => {
        if (item.type != 2) {
          targetData.push(item.id)
        }
        if (item.children && item.children.length > 0) {
          this.expandAllTreeNode(item.children, targetData)
        }
      })
    }
  },
  created() {
    this.getDict(JSON.stringify({code: 'SYS_STATUS'})).then(res => this.dict.status = res.data.data)
    this.getDict(JSON.stringify({code: 'SYS_ORGANIZATION_TYPE'})).then(res => this.dict.type = res.data.data)
    this.reloadTable()
  }
}
</script>
<style scoped lang="less">
  .ant-form-item {
    margin-bottom: 12px;
  }
  .fold{
    width: calc(100% - 12px);
    display: inline-block;
  }
  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
  /deep/.ant-table .ant-table-row-indent + .ant-table-row-expand-icon {
    margin-right: 16px !important;
  }
  .alert{
    margin-bottom: 16px;
    .message{
      a{
        font-weight: 600;
      }
    }
  }
</style>